﻿using UnityEngine;
using UnityEngine.OpenHarmony;

/// <summary>
/// 录音播放
/// </summary>
public class MicroPhoneManager : MonoBehaviour
{
    /// <summary>
    /// 设备长度
    /// </summary>
    public int DeviceLength;
    /// <summary>
    /// 录音频率
    /// </summary>
    public string Frequency = "5000";
    /// <summary>
    /// 录音采样率
    /// </summary>
    public int Samplerate = 44100;
    public int MicSecond = 10;
    string infoLog = "";

    AudioSource _curAudioSource;

    AudioSource CurAudioSource
    {
        get
        {
            if (_curAudioSource == null)
            {
                _curAudioSource = gameObject.AddComponent<AudioSource>();
            }
            return _curAudioSource;
        }
    }

    #region ［public Way］

    /// <summary>
    /// 获取麦克风设备
    /// </summary>
    public void GetMicrophoneDevice()
    {
        string[] mDevice = Microphone.devices;
        DeviceLength = mDevice.Length;
        if (DeviceLength == 0)
            ShowInfoLog("找不到麦克风设备！");
    }

    /// <summary>
    /// 开始录音
    /// </summary>
    public void StartRecordAudio()
    {
        CurAudioSource.Stop();
        CurAudioSource.loop = false;
        CurAudioSource.mute = true;
        CurAudioSource.clip = Microphone.Start(null, true, MicSecond, int.Parse(Frequency));
        while (!(Microphone.GetPosition(null) > 0))
        {

        }
        CurAudioSource.Play();
        ShowInfoLog("开始录音.....");
    }

    /// <summary>
    /// 停止录音
    /// </summary>
    public void StopRecordAudio()
    {
        ShowInfoLog("结束录音.....");
        if (!Microphone.IsRecording(null))
            return;
        Microphone.End(null);
        CurAudioSource.Stop();

    }

    /// <summary>
    /// 回放录音
    /// </summary>
    public void PlayRecordAudio()
    {
        if (Microphone.IsRecording(null))
            return;
        if (CurAudioSource.clip == null)
            return;
        CurAudioSource.mute = false;
        CurAudioSource.loop = false;
        CurAudioSource.Play();
        ShowInfoLog("播放录音.....");
    }

    /// <summary>
    ///  打印录音信息
    /// </summary>
    public void PrintRecordData()
    {
        if (Microphone.IsRecording(null))
            return;
        byte[] data = GetClipData();
        string infoLog = "total length:" + data.Length + " time:" + CurAudioSource.time;
        ShowInfoLog(infoLog);
    }

    /// <summary>
    /// 获取音频数据
    /// </summary>
    /// <returns>The clip data.</returns>
    public byte[] GetClipData()
    {
        if (CurAudioSource.clip == null)
        {
            ShowInfoLog("缺少音频资源！");
            return null;
        }

        float[] samples = new float[CurAudioSource.clip.samples];
        CurAudioSource.clip.GetData(samples, 0);

        byte[] outData = new byte[samples.Length * 2];
        int reScaleFactor = 32767;

        for (int i = 0; i < samples.Length; i++)
        {
            short tempShort = (short)(samples[i] * reScaleFactor);
            byte[] tempData = System.BitConverter.GetBytes(tempShort);

            outData[i * 2] = tempData[0];
            outData[i * 2 + 1] = tempData[1];
        }
        if (outData == null || outData.Length <= 0)
        {

            ShowInfoLog("获取音频数据失败！");
            return null;
        }
        return outData;
    }

    #endregion


    void OnGUI()
    {

        if (DeviceLength == 0)
        {
            if (ShowGUIButton("获取麦克风设备"))
            {
                GetMicrophoneDevice();
            }
            if (ShowGUIButton("申请权限"))
            {
                if (Application.platform == RuntimePlatform.Android)
                {
                    UnityEngine.Android.Permission.RequestUserPermission(UnityEngine.Android.Permission.Microphone);
                }
                else if (Application.platform == RuntimePlatform.OpenHarmony)
                {
                    UnityEngine.OpenHarmony.Permission.RequestUserPermission(UnityEngine.OpenHarmony.Permission.Microphone);
                }
            }
        }
        else if (DeviceLength > 0)
        {
            GUILayout.Label("录音频率:");
            Frequency = GUILayout.TextField(Frequency, GUILayout.Width(Screen.width / 5), GUILayout.Height(Screen.height / 20));
            GUILayout.BeginVertical();

            if (ShowGUIButton("开始录音"))
            {
                StartRecordAudio();
            }
            if (ShowGUIButton("结束录音"))
            {
                StopRecordAudio();
            }
            if (ShowGUIButton("回放录音"))
            {
                PlayRecordAudio();
            }
            if (ShowGUIButton("获取录音数据"))
            {
                PrintRecordData();
            }

            GUILayout.EndVertical();
        }
        GUILayout.Label(infoLog);

    }

    #region [Private Way]

    /// <summary>
    /// 显示GUI 按钮
    /// </summary>
    /// <returns><c>true</c>, if GUI button was shown, <c>false</c> otherwise.</returns>
    /// <param name="buttonName">Button name.</param>
    bool ShowGUIButton(string buttonName)
    {
        return GUILayout.Button(buttonName, GUILayout.Height(Screen.height / 20), GUILayout.Width(Screen.width / 5));
    }

    void ShowInfoLog(string info)
    {
        infoLog += info;
        infoLog += "\r\n";
    }

    #endregion

}